<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\Recharge as RechargeModel;
use app\common\model\Manager as ManagerModel;
use app\common\model\Member as MemberModel;
use app\common\model\Draw as DrawModel;
use app\common\model\Act as ActModel;
use app\common\model\Company as CompanyModel;
use app\common\model\ActsOrder as ActsOrderModel;

/**
 * 充值控制器
 * Class Recharge
 * @package app\home\controller
 */
class Recharge extends Base
{
    /**
     * [getIndex  资金列表]
     * @param type 1乐善好施 2结缘寺院
     * @return json
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $model = new RechargeModel();
        $this->getPageAndSize($param);
        $mem = $this->getMember($param['token']);
        $map = [];
        try{
            $map['memid'] = $mem['id'];
            $map['states'] = 1;
            if($param['type'] == 1){
                $map['item_id'] = ['neq',0];
            }else{
                $map['item_id'] = 0;
                $map['comid'] = ['neq',0];
            }

            $count = $model->getRechargeCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getRechargeByCondition($map,$this->from, $this->size);
            foreach($lists as $k=>$v){
                $lists[$k]['paytime'] = date('Y-m-d H:i:s',$v['paytime']);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '添加失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getSindex  寺院明细]
     * @param type 1乐善好施 2结缘寺院
     * @return json
     * @author [C。]
     */
    public function getSindex()
    {
        $param = input('param.');
        $model = new RechargeModel();
        $memodel = new MemberModel();
        $this->getPageAndSize($param);
        $map = [];
        try{
            $map['comid'] = $param['comid'];
            $map['states'] = 1;

            $count = $model->getRechargeCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getRechargeByCondition($map,$this->from, $this->size);
            foreach($lists as $k=>$v){
                if(!empty($v['memid'])){
                    $member = $memodel->findData($v['memid'],'id','username,img');
                    $lists[$k]['username'] = $member['username'];
                    $http = substr($member['img'],0,4);
                    if($http != 'http'){
                        $member['img'] = config('domain_name').$member['img'];
                    }
                    $lists[$k]['img'] = $member['img'];
                    $lists[$k]['paytime'] = date('Y-m-d H:i:s',$v['paytime']);
                }else{
                    $lists[$k]['username'] = '匿名';
                    $lists[$k]['img'] = config('domain_name').'/Public/nouser.png';
                }
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '添加失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getSindex  提现明细]
     * @param
     * @return json
     * @author [C。]
     */
    public function getDraw()
    {
        $param = input('param.');
        $model = new DrawModel;
        $mmodel = new ManagerModel();

        $mem = $this->getMember($param['token']);
        $this->getPageAndSize($param);
        $map = [];
        try{
            $manager = $mmodel->findData($mem['tel'],'tel','id');
            $map['manager_id'] = $manager['id'];
            $map['comid'] = $param['comid'];
            $field = 'drawamt,addtime,states';
            $count = $model->getDrawCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getDrawByCondition($map,$this->from, $this->size,$field);

            foreach($lists as $k=>$v){
                $lists[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getDrawsub  提现内容]
     * @param
     * @return json
     * @author [C。]
     */
    public function getDrawsub()
    {
        $param = input('param.');
        $model = new RechargeModel;
        $dmodel = new DrawModel;
        try{
            $total_amount = $model->getSum(['states'=>1,'comid'=>$param['comid']],'amt');
            $has_draw = $dmodel->getSum(['comid'=>$param['comid'],'states'=>['neq',2]],'drawamt');
            $ok_draw = $total_amount - $has_draw;
            $data = array(
                'total_amount' => strval($total_amount),
                'has_draw' => strval($has_draw),
                'ok_draw' => strval($ok_draw)
            );
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$data);
    }
    /**
     * [getDrawsub  提现内容]
     * @param
     * @return json
     * @author [C。]
     */
    public function postTodraw()
    {
        $param = input('param.');
        $model = new RechargeModel;
        $dmodel = new DrawModel;
        $mmodel = new ManagerModel;
        $mem = $this->user;
        try{
            $total_amount = $model->getSum(['states'=>1,'comid'=>$param['comid']],'amt');
            $has_draw = $dmodel->getSum(['comid'=>$param['comid'],'states'=>['neq',2]],'drawamt');
            $ok_draw = $total_amount - $has_draw;

            $manager = $mmodel->findData($mem['tel'],'tel','id');
            $maxnum = $dmodel->getMaxnum(['comid'=>$param['comid']],'num');
            $darr = array();
            $darr['manager_id'] = $manager['id'];
            $darr['comid'] = $param['comid'];
            $darr['bef_amt'] = $ok_draw;
            $darr['af_amt'] = $ok_draw - $param['amt'];
            $darr['num'] = 1 + $maxnum;
            $darr['drawamt'] = $param['amt'];
            $darr['ymd'] = date('Ymd');
            $darr['addtime'] = time();
            $darr['states'] = 0;
            $darr['paytime'] = 0;
            $darr['payrmk'] = '';
            $darr['payimg'] = '';
            $darr['tel'] = $mem['tel'];
            $darr['orderno'] = $darr['ymd'] . time() . rand(1111, 9999);
            $dmodel->addData($darr);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '提交失败'.$e->getMessage());
        }
        return admin_json(1, '提交成功');
    }
    /**
     * [postAppPay  微信APP支付]
     * @param type 1乐善好施 2结缘寺院, paytype 1微信app支付 2微信公众号支付 11支付宝app支付,ptype 2结缘寺院  3乐善好施
     * @return json
     * @author [C。]
     */
    public function getAppPay()
    {
        $param = input('param.');
        $model = new ActModel;
        $rmodel = new RechargeModel;
        if($param['app'] == 4){
            $openid = new Openid(config('home.appid'),config('home.secret'));
            $userinfo = $openid->auth_user();
            $param['openid'] = $userinfo['openid'];
            $trade_type = 'JSAPI';
            $appid = config('home.appid');//公众平台appid
            $mch_id = config('home.cmch_id');  //商户号
            $key = config('home.cmch_secret');//商户密钥
        }
        if(empty($param['item_id'])){
            $body = '日行一善';
            $param['ptype'] = 2;
        }else{
            $act = $model->findData($param['item_id'],'id','title,amount,states');
            if($act['states'] != 1){
                return admin_json(-1, '该项目已下线！');
            }

            $has = $rmodel->getSum(['item_id'=>$param['item_id'],'states'=>1],'amt');
            $total = $param['price'] + $has;
            if($total > $act['amount']){
                $need = $act['amount'] - $has;
                return admin_json(-1, '该笔已超出募捐总额！还可捐'.$need.'元');
            }
            $body = $act['title'];
            $param['ptype'] = 3;
        }
        if(empty($param['rmk'])){
            $param['rmk'] = '支持公益！';
        }
        $mch_id = config('home.mch_id');  //商户号
        $key = config('home.mch_secret');//商户密钥
        $out_trade_no = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');//订单号
        $total_fee = request()->param('price');//订单金额

        $param['amt'] = $total_fee;
        $param['title'] = $body;
        $param['myorderno'] = $out_trade_no;

        $total_fee = floatval($total_fee*100);

        if($param['app'] == 1){
            $appid = config('home.kappid');//开放平台appid
            $trade_type = 'APP';

            $orderno = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $data = array();
            $data["appid"] = $appid;
            $data["mch_id"] = $mch_id;
            $data["nonce_str"] = $this->getNonceStr();
            $data["body"] = $body;
            $data["out_trade_no"] = $orderno;
            $data["total_fee"] = $total_fee;
            $data["spbill_create_ip"] = $this->get_client_ip();
            $data["notify_url"] = 'http://www.fushan8.com';
            $data["trade_type"] = $trade_type;
            $response = $this->post('https://api.mch.weixin.qq.com/pay/unifiedorder', $data);
            $data = array();
            $data["appid"] = $appid;
            $data["partnerid"] = $mch_id;
            $data["noncestr"] = $this->getNonceStr();
            $data["prepayid"] = $response["prepay_id"];
            $data["package"] = 'Sign=WXPay';
            $data["timestamp"] = time();
            $data["sign"] = $this->sign($data);
            $id = $this->add($param);
            $data['id'] = $id;
            return admin_json(1, '获取成功',$data);
        }elseif($param['app'] == 2){
            $appid = config('home.appid');//公众平台appid
            $trade_type = 'JSAPI';
        }elseif($param['app'] == 3){
            $appid = config('home.appid');//公众平台appid
            $trade_type = 'JSAPI';
            $mch_id = config('home.cmch_id');  //商户号
            $key = config('home.cmch_secret');//商户密钥
        }
//        $user = new Openid();
//        $userinfo = $user->GetOpenid();
//        $openid = $userinfo['openid'];
        // $openid = new Openid(config('home.appid'),config('home.secret'));
        // $userinfo = $openid->auth_user();
        $openid = $param['openid'];
        $weixinpay = new \WeixinPay\WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee,$trade_type);
        $return = $weixinpay->pay();

        if($return){
            $id = $this->add($param);
            $return['id'] = $id;
            return admin_json(1, '获取成功',$return);
        }else{
            return admin_json(-1, '获取失败');
        }
    }

    /**
     * [getCheck  微信查询订单]
     * @param
     * @return json
     * @author [C。]
     */
    public function getCheck()
    {
        $param = input('param.');
        $model = new RechargeModel();
        try{
            $orderno = $model->findData($param['id'],'id','myorderno');
            if($param['app'] == 1){
                $appid = config('home.kappid');//开放平台appid
                $mch_id = config('home.mch_id');  //商户号
                $key = config('home.mch_secret');  //商户密钥
            }elseif($param['app'] == 2){
                $appid = config('home.appid');//开放平台appid
                $mch_id = config('home.mch_id');  //商户号
                $key = config('home.mch_secret');  //商户密钥
            }elseif($param['app'] == 3){
                $appid = config('home.appid');//开放平台appid
                $mch_id = config('home.cmch_id');  //商户号
                $key = config('home.cmch_secret');  //商户密钥
            }
            $out_trade_no = $orderno['myorderno'];
            $weixinpay = new \WeixinPay\WeixinPay($appid,$openid = '',$mch_id,$key,$out_trade_no,$body = '',$total_fee = '');
            $return = $weixinpay->check();
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '查询失败'.$e->getMessage());
        }
        if($return){
            if($return['result_code'] == "SUCCESS"){
                if($return['trade_state'] == 'SUCCESS'){
                    return admin_json(1, '订单支付成功');
                }else{
                    return admin_json(-1, '订单支付失败');
                }
            }else{
                return admin_json(-1, '订单支付失败');
            }
        }else{
            return admin_json(-1, '订单支付失败');
        }
    }
    /**
     * [postAliAppPay  支付宝APP支付]
     * @param type 1乐善好施 2结缘寺院, paytype 1微信app支付 2微信公众号支付 11支付宝app支付,ptype 2结缘寺院  3乐善好施
     * @return json
     * @author [C。]
     */
    public function postAliAppPay()
    {
        $param = input('param.');

    }
    //修改订单状态
    public function postEdit()
    {
        $param = input('param.');
        $model = new RechargeModel;
        try{
            $data = $model->findData($param['id'],'id','ordertime');
            $time = time() - $data['ordertime'];
            if($time > 60*60){
                return admin_json(-1, '不及胜而过之！');
            }
            $model->editData(['id'=>$param['id'],'states'=>1,'paytime'=>time()]);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    //添加
    public function add($data)
    {
        $model = new RechargeModel();
        $mem = $this->getMember($data['token']);
        $arr = array(
            'comid' => $data['comid'],
            'memid' => $mem['id'],
            'ptype' => $data['ptype'],
            'title' => $data['title'],
            'amt' => $data['amt'],
            'paytype' => $data['paytype'],
            'myorderno' => $data['myorderno'],
            'ordertime' => time(),
        );
        if(!empty($data['item_id'])){
            $arr['item_id'] = $data['item_id'];
        }
        if(!empty($data['rmk'])){
            $arr['rmk'] = $data['rmk'];
        }
        if(!empty($data['name'])){
            $arr['name'] = $data['name'];
        }
        if(!empty($data['tel'])){
            $arr['tel'] = $data['tel'];
        }
        $id = $model->addData($arr);
        return $id;
    }
    //添加
    public function create_order()
    {
        $param = input('param.');
        $model = new RechargeModel();
        $cmodel = new CompanyModel;
        $company = $cmodel->findData($param['comid'],'id','mch_id,much_secret,wx_appid,wx_secret,is_son');
        if($company['is_son'] == 1){
            if(empty($company['mch_id']) || empty($company['wx_appid'])){
                return admin_json(2, '暂未开通');
            }
        }else{
            if(empty($company['wx_appid']) || empty($company['wx_secret']) || empty($company['mch_id']) || empty($company['much_secret'])){
                return admin_json(2, '暂未开通');
            }
        }
        $mem = $this->user;
        $arr = array(
            'comid' => $param['comid'],
            'memid' => $mem['id'],
            'title' => $param['title'],
            'amt' => $param['amt'],
            'paytype' => $param['paytype'],
            'myorderno' => date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0'),//订单号,
            'ordertime' => time(),
        );
        if(!empty($param['item_id'])){
            $arr['item_id'] = $param['item_id'];
        }
        if(!empty($param['rmk'])){
            $arr['rmk'] = $param['rmk'];
        }
        $id = $model->addData($arr);
        return admin_json(1, '创建成功',$id);
    }
    /**
     * [pay_success  支付成功]
     * @param
     * @author [C。]
     * @return json
     */
    public function pay_success()
    {
        $param = input('param.');
        $amodel = new ActModel;
        $rmodel = new RechargeModel();
        $omodel = new ActsOrderModel;
        $model = new RechargeModel;
        try{
            $data = $model->findData($param['id'],'id','item_id,ordertime');
            $time = time() - $data['ordertime'];
            if($time > 60*60){
                return admin_json(-1, '不及胜而过之！');
            }
            $model->editData(['id'=>$param['id'],'states'=>1,'paytime'=>time()]);
            $act = $amodel->findData($data['item_id'],'id','amount');
            $hasamount1 = $omodel->getAlreadyRaising($data['item_id']);
            $hasamount2 = $rmodel->getAlreadyRaising($data['item_id']);
            $hasamount = $act['amount'] - $hasamount1 - $hasamount2;
            if($hasamount == 0){
                $amodel->editData(['id'=>$data['item_id'],'states'=>3]);
            }
        }catch (\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败' . $e->getMessage());
        }
        return admin_json(1, '修改成功');
    }

    private function getNonceStr() {
        return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 32);
    }
    private function get_client_ip() {
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
        }

        return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
    }
    /**
     * 数据签名
     * @param $data
     * @return string
     */
    private function sign($data) {
        ksort($data);
        $string1 = "";
        foreach ($data as $k => $v) {
            if ($v && trim($v) != '') {
                $string1 .= "$k=$v&";
            }
        }
        $stringSignTemp = $string1 . "key=" . config('home.mch_secret');
        $sign = strtoupper(md5($stringSignTemp));
        return $sign;
    }
    private function post($url, $data, $cert = false) {
        if (!isset($data['sign'])) {
            $data["sign"] = $this->sign($data);
        }

        $xml = $this->array2xml($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        // if ($cert == true)
        // {
        //     //使用证书：cert 与 key 分别属于两个.pem文件
        //     curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        //     curl_setopt($ch, CURLOPT_SSLCERT, $this->_config['sslcertPath']);
        //     curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        //     curl_setopt($ch, CURLOPT_SSLKEY, $this->_config['sslkeyPath']);
        // }
        $content = curl_exec($ch);
        $array = $this->xml2array($content);
        return $array;
    }
    private function array2xml($array) {
        $xml = "<xml>" . PHP_EOL;
        foreach ($array as $k => $v) {
            if ($v && trim($v) != '') {
                $xml .= "<$k><![CDATA[$v]]></$k>" . PHP_EOL;
            }

        }
        $xml .= "</xml>";
        return $xml;
    }
    private function xml2array($xml) {
        $array = array();
        $tmp = null;
        try
        {
            $tmp = (array) simplexml_load_string($xml);
        } catch (Exception $e) {

        }
        if ($tmp && is_array($tmp)) {
            foreach ($tmp as $k => $v) {
                $array[$k] = (string) $v;
            }
        }
        return $array;
    }

}